<template>
  <div class="app-container home">
    <el-row :gutter="20" class="panel-group-header">
       <el-col :span="12">
         <h2>平台数据概览</h2>
       </el-col>
       <el-col :span="12" style="text-align: right;">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-connection"
            plain
            @click="goToApiPlatform"
          >访问API开放平台</el-button>
       </el-col>
    </el-row>

    <el-row :gutter="40" class="panel-group">
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-api">
            <i class="el-icon-files card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">总API数</div>
            <count-to :start-val="0" :end-val="totalApis" :duration="2600" class="card-panel-num" />
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-calls">
             <i class="el-icon-data-line card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">今日调用</div>
            <count-to :start-val="0" :end-val="todayCalls" :duration="3000" class="card-panel-num" />
          </div>
        </div>
      </el-col>
       <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-users">
            <i class="el-icon-user card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">活跃用户</div>
            <count-to :start-val="0" :end-val="activeUsers" :duration="3200" class="card-panel-num" />
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
        <div class="card-panel">
          <div class="card-panel-icon-wrapper icon-errors">
            <i class="el-icon-warning-outline card-panel-icon" />
          </div>
          <div class="card-panel-description">
            <div class="card-panel-text">错误率</div>
            <count-to :start-val="0" :end-val="errorRate" :duration="3600" :decimals="2" suffix="%" class="card-panel-num" />
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div ref="realtimeChart" style="height: 400px"></div>
         </el-card>
       </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  ToolboxComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import CountTo from 'vue-count-to';
import { debounce } from '@/utils';
import {
    getDashboardSummary,
    getCallsTrend,
    getStatusDistribution,
    getTopApis,
    getRealtimeStats
} from '@/api/backend/dashboard';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  ToolboxComponent,
  LineChart,
  CanvasRenderer
]);

export default {
  name: "BackendIndexDashboard",
  components: { CountTo },
  data() {
    return {
      totalApis: 0,
      todayCalls: 0,
      activeUsers: 0,
      errorRate: 0,

      realtimeChart: null,
      timer: null,
      loading: false,
      refreshInterval: 5000, // 可配置的刷新间隔

      $_resizeHandler: null
    };
  },
  mounted() {
    this.initCharts();
    this.fetchData();
    // 使用配置的刷新间隔
    this.timer = setInterval(this.fetchData, this.refreshInterval);
    
    this.$_resizeHandler = debounce(() => {
      if (this.realtimeChart) {
        this.realtimeChart.resize();
      }
    }, 100);
    window.addEventListener('resize', this.$_resizeHandler);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.realtimeChart) {
      this.realtimeChart.dispose();
    }
    window.removeEventListener('resize', this.$_resizeHandler);
  },
  methods: {
    initCharts() {
      try {
        this.realtimeChart = echarts.init(this.$refs.realtimeChart);
      } catch (error) {
        console.error('图表初始化失败:', error);
        this.$message.error('图表初始化失败: ' + error.message);
      }
    },
    async fetchData() {
      if (this.loading) return;
      
      this.loading = true;
      try {
        const [summaryRes, realtimeRes] = await Promise.all([
          getDashboardSummary(),
          getRealtimeStats()
        ]);

          if (summaryRes.code === 200 && summaryRes.data) {
            const summaryData = summaryRes.data;
            this.totalApis = summaryData.totalApis || 0;
            this.todayCalls = summaryData.todayCalls || 0;
            this.activeUsers = summaryData.activeUsers || 0;
            this.errorRate = summaryData.errorRate || 0;
          }

        if (realtimeRes.code === 200 && realtimeRes.data) {
          this.updateRealtimeChart(realtimeRes.data);
          } else {
          console.warn('No realtime data available:', realtimeRes);
          this.showEmptyChart(this.realtimeChart, '实时调用监控');
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        this.$message.error('加载数据失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    showEmptyChart(chart, title) {
      if (!chart) return;
      
      const option = {
        title: {
          text: title,
          subtext: '暂无数据',
          left: 'center',
          top: 'center'
        }
      };
      chart.setOption(option);
    },
    updateRealtimeChart(data) {
      if (!this.realtimeChart) return;
      
      if (!data.timePoints || data.timePoints.length === 0) {
        this.showEmptyChart(this.realtimeChart, '实时调用监控');
        return;
      }

      const option = {
        title: {
          text: '实时调用监控',
           left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['调用量', '错误率', '响应时间'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '8%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.timePoints.map(point => point.timePoint)
        },
        yAxis: [
          {
            type: 'value',
            name: '调用量',
            position: 'left',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#5470C6'
              }
            },
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '错误率(%)',
            position: 'right',
            offset: 80,
            max: 100,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#EE6666'
              }
            },
            axisLabel: {
              formatter: '{value}%'
            }
          },
          {
            type: 'value',
            name: '响应时间(ms)',
            position: 'right',
            axisLine: {
                show: true,
              lineStyle: {
                color: '#91CC75'
              }
            },
            axisLabel: {
              formatter: '{value}ms'
            }
          }
        ],
        series: [
          {
            name: '调用量',
            type: 'line',
            yAxisIndex: 0,
            smooth: true,
            itemStyle: {
              color: '#5470C6'
            },
            data: data.timePoints.map(point => point.callCount)
          },
          {
            name: '错误率',
            type: 'line',
            yAxisIndex: 1,
            smooth: true,
            itemStyle: {
              color: '#EE6666'
            },
            data: data.timePoints.map(point => point.errorRate)
          },
          {
            name: '响应时间',
            type: 'line',
            yAxisIndex: 2,
            smooth: true,
            itemStyle: {
              color: '#91CC75'
            },
            data: data.timePoints.map(point => point.avgResponseTime)
          }
        ]
      };
      this.realtimeChart.setOption(option);
    },
    goToApiPlatform() {
      this.$router.push('/front/home')
    }
  }
};
</script>

<style scoped lang="scss">
.home {
  padding: 20px;
  background-color: #f0f2f5;

  .panel-group-header {
      margin-bottom: 20px;
      h2 {
        margin: 0;
        font-size: 20px;
      }
  }

  .panel-group {
    margin-bottom: 20px;

    .card-panel-col {
      margin-bottom: 20px;
    }

    .card-panel {
      height: 108px;
      cursor: pointer;
      font-size: 12px;
      position: relative;
      overflow: hidden;
      color: #666;
      background: #fff;
      box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
      border-color: rgba(0, 0, 0, .05);
      border-radius: 4px;

      &:hover {
        .card-panel-icon-wrapper {
          color: #fff;
        }

        .icon-api {
          background: #40c9c6;
        }

        .icon-calls {
          background: #36a3f7;
        }

        .icon-users {
           background: #f4516c;
        }

        .icon-errors {
           background: #e6a23c;
        }
      }

      .icon-api {
        color: #40c9c6;
      }

      .icon-calls {
        color: #36a3f7;
      }
       .icon-users {
         color: #f4516c;
      }
       .icon-errors {
         color: #e6a23c;
      }

      .card-panel-icon-wrapper {
        float: left;
        margin: 14px 0 0 14px;
        padding: 16px;
        transition: all 0.38s ease-out;
        border-radius: 6px;
      }

      .card-panel-icon {
        float: left;
        font-size: 48px;
      }

      .card-panel-description {
        float: right;
        font-weight: bold;
        margin: 26px;
        margin-left: 0px;

        .card-panel-text {
          line-height: 18px;
          color: rgba(0, 0, 0, 0.45);
          font-size: 16px;
          margin-bottom: 12px;
        }

        .card-panel-num {
          font-size: 20px;
        }
      }
    }
  }
}

@media (max-width:550px) {
  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;
    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>

